import {
    getProductist,
    getBannertist,
    getCompanytist,
    getNewsList,
    getlistzj,
} from './../../api/article'
import {
    getShowCoupon
} from './../../api/user'
import {
    formatTime2
} from '../../utils/util'
// pages/home/home.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        showPrivacyModal: false,
        privacyAgreed: false,
        banners: [],
        companys: [],
        products: [],
        news: [],
        lastPage: false,
        params: {
            type: 1,
            pageIndex: 1,
            pageSize: 6,
            state: 2
        },
        list: [],
        show: false,
        counpon: null,
        showPrivacy: true,
    },
    onShow() {
        getShowCoupon({}).then(res => {
            console.log(res, 'xxxxxxxxxx')
            if (res && !res.status) {
                this.setData({
                    counpon: res.content,
                    show: true
                })
            }
        })
    },
    handleClose() {
        this.setData({
            show: false
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    handleGET() {
        if (!wx.getStorageSync('token')) {
            wx.showModal({
                title: '提示',
                content: '您还未登录，请登录后领取',
                complete: (res) => {
                    if (res.cancel) {

                    }

                    if (res.confirm) {
                        wx.switchTab({
                            url: '/pages/my/my',
                        })
                    }
                }
            })
        } else {
            wx.navigateTo({
                url: '/pages/coupon/coupon',
            })
            this.handleClose()
        }
    },
    onLoad(options) {
        console.log(options)
        this.init()
        this.initzhuanjiaList()
        


        // 从全局变量获取是否需要弹窗
        const app = getApp();
        if (app.globalData.needShowPrivacyModal) {
            this.setData({
                showPrivacyModal: true
            });
        } else {
            this.setData({
                privacyAgreed: true
            });
        }
    },
    // 处理用户同意
    handleAgree() {
        this.setData({
            showPrivacyModal: false,
            privacyAgreed: true
        });
        const app = getApp();
        app.globalData.needShowPrivacyModal = false
    },

    // 处理用户拒绝
    handleRefuse() {
        this.setData({
            showPrivacyModal: false
        });
    },
    checkPrivacyStatus() {
        wx.getPrivacySetting({
            success: (res) => {
                console.log('隐私政策状态:', res);
                console.log('是否需要授权:', res.needAuthorization);
                console.log('政策名称:', res.privacyContractName);
                if (res.needAuthorization) {
                    console.log('用户尚未同意隐私政策，即将触发原生弹窗');
                    this.triggerPrivacyRelatedApi();
                }
            },
            fail: (err) => {
                console.error('获取隐私设置失败:', err);
            }
        });
    },
    // 触发需要隐私授权的接口
    triggerPrivacyRelatedApi() {
        wx.getUserProfile({
            desc: '用于完善会员资料',
            success: (res) => {
                console.log('用户信息获取成功:', res);
            },
            fail: (err) => {
                console.error('用户信息获取失败:', err);
            }
        });
    },
    // 用户同意隐私政策后的回调
  
    async init() {
        // const products = await getProductist({
        //     pageIndex: 1,
        //     pageSize: 50,
        //     state: 1
        // })
        // if (products.content.length) {
        //     products.content.forEach(el => {
        //         el.imgs ? el.imgs = JSON.parse(el.imgs) : el.imgs = []
        //         if (el.imgs[0]) {
        //             el.cover = el.imgs[0]
        //         }
        //     })
        // }
        const banners = await getBannertist({
            pageIndex: 1,
            pageSize: 100,
            state: 1
        })
        // const companys = await getCompanytist({
        //     pageIndex: 1,
        //     pageSize: 4,
        //     news: 2
        // })
        // const news = await getNewsList({
        //     pageIndex: 1,
        //     pageSize: 100,
        //     state: 1
        // })
        // if (news.content) {
        //     news.content.forEach(el => {
        //         el.updateTime = formatTime2(el.updateTime)
        //     })
        // }
        this.setData({
            // products: products.content,
            banners: banners.content,
            // companys: companys.content,
            // news: news.content
        })
    },
    async initzhuanjiaList() {
        const res = await getlistzj(this.data.params)
        if (res.content && res.content.length) {
            res.content.forEach(el => {
                el.goodAt = el.goodAt.split(',')
            })
        }

        this.setData({
            list: this.data.list.concat(res.content),
            lastPage: res.lastPage,
        })
    },
    handleLink(e) {
        const item = e.currentTarget.dataset.item
        console.log(item)
        if (item.type == 1) {
            wx.showToast({
                title: '外部链接暂不可用',
                icon: 'none'
            })
        } else if (item.type == 2) {
            // 商品。
            wx.navigateTo({
                url: `/pages/product/product?id=${item.data}`,
            })
        } else if (item.type == 3) {
            // 知识 
            wx.navigateTo({
                url: `/pages/article/article?id=${item.data}&type=1`,
            })
        } else if (item.type == 4) {
            //课程 。
            wx.navigateTo({
                url: `/pages/paly/paly?id=${item.data}`,
            })
        } else {
            // 企业
            wx.navigateTo({
                url: `/pages/company/company?id=${item.data}`,
            })
        }

    },
    handleMore1() {
        wx.switchTab({
            url: '/pages/enterprise/enterprise',
        })
    },
    handleMore2() {
        wx.switchTab({
            url: '/pages/expert/expert',
        })
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        return {
            title: '建享经纪',
            path: 'pages/company/company?id=1111'
        }
    },
    handleDetailjjr(e) {
        const item = e.currentTarget.dataset.item
        wx.navigateTo({
            url: `/pages/jjrdetail/jjrdetail?item=${JSON.stringify(item)}`,
        })
    },
    handleDetailCompany(e) {
        const item = e.currentTarget.dataset.item
        wx.navigateTo({
            url: `/pages/company/company?id=${item.companyId}`,
        })
    },
    handleDetail(e) {
        const item = e.currentTarget.dataset.item
        wx.navigateTo({
            url: `/pages/product/product?item=${JSON.stringify(item)}`,
        })
    },
    handleDetailNews(e) {

        const id = e.currentTarget.dataset.item.id
        wx.navigateTo({
            url: `/pages/article/article?id=${id}&type=2`,
        })
    },
    onPullDownRefresh() {
        this.data.params.pageIndex = 1
        this.setData({
            list: [],
            lastPage: false
        })
        this.initzhuanjiaList()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        if (!this.data.lastPage) {
            this.setData({
                ['params.pageIndex']: this.data.params.pageIndex += 1
            })
            this.initzhuanjiaList()
        }
    },

})